package site.xuxingcan.autologin;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xuxingcan on 2016/9/7.
 */
public class KeyUtil {
    private static Handler mHandler = new Handler(Looper.getMainLooper());
    private static Gson gson = new Gson();

    public static void getYunMaKey(final CallBack callBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("username", SharedPreferenceUtil.getInstance().getYunmaUser());
                params.put("password", SharedPreferenceUtil.getInstance().getYunmaPwd());
                params.put("appid", "1");
                params.put("appkey", "22cc5376925e9387a23cf797cb9ba745");
                params.put("filename", "key_cut.png");
                params.put("codetype", "1004");
                params.put("timeout", "60");
                Map<String, File> files = new HashMap<String, File>();
                files.put("file", new File(MyApplication.mContext.getFilesDir(), "key_cut.png"));
                try {
                    String key = post("http://api.yundama.com/api.php?method=upload", params, files);
                    Log.i("xuxingcan", "key = " + key);
                    final YunmaModel yunmaModel = gson.fromJson(key, YunmaModel.class);
                    if (yunmaModel == null) {
                        throw new Exception("null");
                    } else {
                        if (TextUtils.isEmpty(yunmaModel.getText())) {
                            int times = 0;
                            while (true) {
                                times++;
                                Thread.sleep(5 * 1000);
                                String result = get("http://api.yundama.com/api.php?cid=" + yunmaModel.getCid() + "&method=result");
                                final YunmaModel model = gson.fromJson(result, YunmaModel.class);
                                if (model != null && !TextUtils.isEmpty(model.getText())) {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (callBack != null) {
                                                callBack.onFinish(model.getText());
                                            }
                                        }
                                    });
                                    return;
                                }
                                if (times > 10) {
                                    throw new Exception("null");
                                }
                            }
                        } else {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (callBack != null) {
                                        callBack.onFinish(yunmaModel.getText());
                                    }
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.onFinish(null);
                            }
                        }
                    });
                }
            }
        }).start();
    }

    public static class YunmaModel {

        /**
         * ret : 0
         * cid : 1147558968
         * text : bkgt
         */

        private int ret;
        private String cid;
        private String text;

        public int getRet() {
            return ret;
        }

        public void setRet(int ret) {
            this.ret = ret;
        }

        public String getCid() {
            return cid;
        }

        public void setCid(String cid) {
            this.cid = cid;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    }

    public static void getLianZongKey(final CallBack callBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("user_name", SharedPreferenceUtil.getInstance().getLianZongUser());
                params.put("user_pw", SharedPreferenceUtil.getInstance().getLianZongPwd());
                params.put("yzm_minlen", "4");
                params.put("yzm_minlen", "4");
                params.put("yzmtype_mark", "0");
                params.put("zztool_token", SharedPreferenceUtil.getInstance().getLianZongUser());
                Map<String, File> files = new HashMap<String, File>();
                files.put("upload", new File(MyApplication.mContext.getFilesDir(), "key_cut.png"));
                try {
                    String key = post("http://bbb4.hyslt.com/api.php?mod=php&act=upload", params, files);
                    Log.i("xuxingcan", "key = " + key);
                    final LianZongModel model = gson.fromJson(key, LianZongModel.class);
                    if (model == null || model.getData() == null) {
                        throw new Exception("null");
                    }
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.onFinish(model.getData().getVal());
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.onFinish(null);
                            }
                        }
                    });
                }
            }
        }).start();
    }

    public static class LianZongModel {

        /**
         * result : true
         * data : {"id":"4661731d94","val":"YMAL"}
         */

        private boolean result;
        /**
         * id : 4661731d94
         * val : YMAL
         */

        private DataBean data;

        public boolean isResult() {
            return result;
        }

        public void setResult(boolean result) {
            this.result = result;
        }

        public DataBean getData() {
            return data;
        }

        public void setData(DataBean data) {
            this.data = data;
        }

        public static class DataBean {
            private String id;
            private String val;

            public String getId() {
                return id;
            }

            public void setId(String id) {
                this.id = id;
            }

            public String getVal() {
                return val;
            }

            public void setVal(String val) {
                this.val = val;
            }
        }
    }

    public interface CallBack {
        void onFinish(String s);
    }

    public static String get(String url) throws Exception {
        URL realUrl = new URL(url);
        URLConnection connection = realUrl.openConnection();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
        String line;
        String result = "";
        while ((line = in.readLine()) != null) {
            result += line;
        }
        in.close();
        return result;
    }

    /**
     * 通过拼接的方式构造请求内容，实现参数传输以及文件传输
     */
    public static String post(String url, Map<String, String> params, Map<String, File> files) throws IOException {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setConnectTimeout(60 * 1000);
        conn.setReadTimeout(60 * 1000);
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);     // 首先组拼文本类型的参
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());     // 发送文件数据
        if (files != null) for (Map.Entry<String, File> file : files.entrySet()) {
            StringBuilder sb1 = new StringBuilder();
            sb1.append(PREFIX);
            sb1.append(BOUNDARY);
            sb1.append(LINEND);
            sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND);
            sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
            sb1.append(LINEND);
            outStream.write(sb1.toString().getBytes());
            InputStream is = new FileInputStream(file.getValue());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();
            outStream.write(LINEND.getBytes());
        }     // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();     // 得到响应码
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        StringBuilder sb2 = new StringBuilder();
        if (res == 200) {
            int ch;
            while ((ch = in.read()) != -1) {
                sb2.append((char) ch);
            }
        }
        outStream.close();
        conn.disconnect();
        return sb2.toString();
    }

    public final static String Money(int index) throws IOException {
        String[] url = new String[]{
                "http://bbb4.hyslt.com/api.php?mod=php&act=point",
                "http://api.yundama.com/api.php?method=balance"
        };
        Map<String, String> paramMap = new HashMap<>();
        if (index == 0) {
            paramMap.put("user_name", SharedPreferenceUtil.getInstance().getLianZongUser());
            paramMap.put("user_pw", SharedPreferenceUtil.getInstance().getLianZongPwd());
        } else {
            paramMap.put("username", SharedPreferenceUtil.getInstance().getYunmaUser());
            paramMap.put("password", SharedPreferenceUtil.getInstance().getYunmaPwd());
            paramMap.put("appid", "1");
            paramMap.put("appkey", "22cc5376925e9387a23cf797cb9ba745");
            paramMap.put("method", "balance");
        }
        String ret = post(url[index], paramMap, null);
        if (ret.equals("")) {
            return "余额:未成功获取";
        }
        try {
            JSONObject js = new JSONObject(ret);
            if (index == 0) {
                return "余额:" + js.get("data");
            } else {
                return "余额:" + js.get("balance");
            }
        } catch (Exception e) {

        }
        return "余额:数据获取失败";
    }
}
